import { ethers } from "ethers";
import contractJson from "../contracts/NftMarket.json";

let provider;
let signer;
let contract;

// 初始化 provider、signer、合约实例
export function initContract() {
  // 浏览器需已安装/连接 MetaMask
  if (!window.ethereum) throw new Error("No wallet detected");
  provider = new ethers.BrowserProvider(window.ethereum);
  return provider.send("eth_requestAccounts", []).then(async () => {
    signer = await provider.getSigner();
    contract = new ethers.Contract(
      contractJson.address,
      contractJson.abi,
      signer
    );
    return contract;
  });
}

// 铸造 NFT
export async function mintToken(tokenURI) {
  if (!contract) await initContract();
  const tx = await contract.mintToken(tokenURI);
  return await tx.wait();
}

// 上架 NFT
export async function listItem(tokenId, priceWei) {
  if (!contract) await initContract();
  const tx = await contract.listItem(tokenId, priceWei);
  return await tx.wait();
}

// 获取在售 NFT 列表
export async function getAllListedItems() {
  if (!contract) await initContract();
  return await contract.getAllListedItems();
}

// 购买 NFT
export async function buyNft(tokenId, priceWei) {
  if (!contract) await initContract();
  const tx = await contract.buyNft(tokenId, { value: priceWei });
  return await tx.wait();
}

export async function getMyNfts(address) {
  if (!contract) await initContract();
  return await contract.getMyNfts(address);
}
